
package com.hc.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import javax.annotation.Resource;
import javax.print.attribute.standard.MediaSize.Other;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.dsig.SignatureMethod;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.hc.domain.Article;
import com.hc.service.IArticleService;
import com.hc.util.AuthToken;
import com.hc.util.CookieUtils;
import com.hc.util.FileUtils;
import com.hc.util.IdWorker;
import com.hc.util.LoggerUtil;
import com.hc.util.OtherUtils;

@Controller
@RequestMapping("Article")
public class ArticleController extends BaseController{
	@Resource
	private IArticleService articleService;
	/**
	 * 
	 * @Description： 保存文章
	 * @param req
	 * @param resp
	 * @param title 标题
	 * @param keywords 关键字
	 * @param file 缩略图
	 * @param subContent 摘要
	 * @param subTitle 子标题
	 * @param type 类型
	 * @param tag 标签
	 * @param content 正文
	 * @param status 状态码
	 * @return
	 * @author:  
	 * @since: 2017年8月28日 下午3:10:53
	 */
	@ResponseBody
	@RequestMapping(value="saveArticle",method=RequestMethod.POST)
	public JSON saveArticle(HttpServletRequest req,HttpServletResponse resp,
			@RequestParam(value = "title", required = true) String title,
			@RequestParam(value = "keywords", required = true) String keywords,
			@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value = "subContent", required = false) String subContent,
			@RequestParam(value = "subTitle", required = true) String subTitle,
			@RequestParam(value = "type", required = true) String type,
			@RequestParam(value = "tag", required = true) String tag,
			@RequestParam(value = "content", required = true) String content,
			@RequestParam(value = "status", required = true) int status,
			@RequestParam(value = "id", required = false) Integer id) {
			String token = CookieUtils.getCookie(req, resp, "token", false);
			Integer userId =Integer.parseInt(AuthToken.getInfo(token, 1));
			String urlPath = "";
			Article art = null;
			if (id==null||id==0) {
				if (file==null||file.isEmpty()) {
					return Message(ERROR, "请上传缩略图", null);
				}
				art = new Article();
			}else {
				art = articleService.getById(id);
				if (art==null) {
					return Message(ERROR, "该文章已删除", null);
				}
				urlPath = art.getSubImg();
			}
			String curDate = OtherUtils.getCurrentDate();
			String newFileName = IdWorker.createId();
			String ext = "gif,jpg,jpeg,png,bmp";
			String path = req.getContextPath();
			String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
			FileOutputStream fos = null;
			InputStream in = null;
			
			File f = new File(FILE_PATH + "Article/");
			if (!f.exists()) {
				f.mkdirs();
			}
			
			if (file!=null&&!file.isEmpty()) {
				try {
					fos = new FileOutputStream(FILE_PATH + "Article/" + newFileName);
					in = file.getInputStream();
					String fileExt = FileUtils.getFileTypeByStream(IOUtils.toByteArray(file.getInputStream()));
					if (isEmpty(fileExt)||ext.indexOf(fileExt)<0) {
						return Message(ERROR, "未知图片类型（合法格式:PNG/JPEG/JPG/GIF/BMP）", null);
					}
					int b = 0;
					while ((b = in.read()) != -1) {
						fos.write(b);
					}
					urlPath = basePath + "File/getFile/" + "Article/" + newFileName;
				} catch (Exception e) {
					return LoggerUtil.logInfo(e, "服务器异常，请联系管理员");
				} finally {
					try {
						if (fos != null) {
							fos.close();
						}
						if (in != null) {
							in.close();
						}
					} catch (Exception e2) {
						LoggerUtil.error(e2);
					}
				}
			}
			
			art.setEditorId(userId);
			if (status==1) {
				art.setPublishUserId(userId);
				art.setPublishDate(curDate);
			}
			art.setStatus(status);
			art.setTitle(title);
			art.setContent(content);
			art.setCreateDate(curDate);
			art.setKeyWords(keywords);
			if (isEmpty(subContent)) {
				subContent = content.substring(0,80);
			}
			art.setSubContent(subContent);
			art.setSubImg(urlPath);
			art.setTag(tag);
			art.setSubTitle(subTitle);
			art.setType(type);
			art.setViewCount(0);
			if (id==null||id==0) {
				articleService.save(art);
			}else {
				articleService.update(art);
			}
			return Message(SUCCESS, "文章保存成功", null);
	}
	/**
	 * 
	 * @Description： 分页查询数据
	 * @param req
	 * @param resp
	 * @param page 页码
	 * @param count 个数
	 * @param type 文章类型
	 * @return
	 * @author:  
	 * @since: 2017年8月28日 下午4:10:21
	 */
	@ResponseBody
	@RequestMapping(value="getArticle",method=RequestMethod.POST)
	public JSON getArticle(HttpServletRequest req,HttpServletResponse resp,
			@RequestParam(value = "page", required = true) int page,
			@RequestParam(value = "count", required = true) int count,
			@RequestParam(value = "type", required = true) String type,
			@RequestParam(value = "words", required = false) String words) {
			List<Article> arts = null;
			if(isEmpty(words)) {
				arts = articleService.findPageByType(page,count,type);
			}else {
				arts = articleService.findPageByLikeSql(page,count,type,words);
			}
			if (arts==null||arts.size()<=0) {
				return Message(NO_MORE_INFO, "没有更多数据", null);
			}
			return Message(SUCCESS, "获取数据成功", arts);
	}
	/**
	 * 
	 * @Description： 删除，逻辑上删除
	 * @param req
	 * @param resp
	 * @param id
	 * @return
	 * @author:  
	 * @since: 2017年8月28日 下午6:14:23
	 */
	@ResponseBody
	@RequestMapping(value="del",method=RequestMethod.POST)
	public JSON del(HttpServletRequest req,HttpServletResponse resp,
			@RequestParam(value = "id", required = true) int id) {
		Article art = articleService.getById(id);
		if (art==null) {
			return Message(ERROR, "该文章已删除", null);
		}
		art.setStatus(99);
		articleService.update(art);
		return Message(SUCCESS, "删除成功", null);
	}
	
}

